<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
</head>
<body>
<input type="button" value="红">
<input type="button" value="蓝">
<input type="button" value="绿">
<script type="text/javascript">
var cookie = {
  add: function(key, val, h) {
    var str = key + "=" + escape(val);
    if (h > 0) { //如果h为0的时候就是不设置过期时间，浏览器关闭的时候cookie自动删除
      var data = new Date();
      var ms = h * 3600 * 1000;
      data.setTime(data.getTime() + ms); //设置了世界时间
      str += "; expires=" + data.toGMTString(); //根据世界时间，把 Date 对象转换为字符串
      document.cookie = str;
      alert("添加成功");
    }
  },
  get: function(key) {
    var arrStr = document.cookie.split("; ");
    for (var i = 0; i < arrStr.length; i++) {
      var temp = arrStr[i].split("=");
      if (temp[0] == key) {
        return unescape(temp[1]);
      }
    }
  },
  del: function(key) {
    var data = new Date();
    data.setTime(-10000);
    document.cookie = key + "=a; expires=" + data.toGMTString();
  
  },
  getAll: function() {
    var str = document.cookie;
    var arr = document.cookie.split(";")
    var valArr = []
    if (!str) {
      alert("没有任何cookie");
    } else {
  
      for (var i = 0; i < arr.length; i++) {
        var temp = arr[i].split("=");
        valArr.push("key:" + temp[0] + ", val:" + unescape(temp[1]));
      }
      return valArr;
    }
  }
};
  
var btn = document.getElementsByTagName("input");
  
btn[0].onclick = function() {
  document.body.style.background = "red";
  var se = document.body.style.background;
  cookie.add("background", se, 24);
}
  
  
btn[1].onclick = function() {
  document.body.style.background = "blue";
  var se = document.body.style.background;
  cookie.add("background", se, 24);
}
  
btn[2].onclick = function() {
  document.body.style.background = "green";
  var se = document.body.style.background;
  cookie.add("background", se, 24);
}
if (cookie.get("background")) {
  document.body.style.background = cookie.get("background");
}    
</script>
</body>
  
</html>